package net.mlike.openssp.server.api.system;

import net.mlike.openssp.server.dto.Message;
import net.mlike.openssp.server.entity.system.Role;
import net.mlike.openssp.server.search.system.role.RoleSearch;
import net.mlike.openssp.server.service.system.RoleService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by wallellen@hotmail.com on 5/26/18.
 */
@RestController
@RequestMapping("/api/roles")
public class RestRoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public Message list(RoleSearch search) {
        Page<Role> roles = roleService.findBySearch(search);
        return Message.success(roles);
    }

    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public Message save(Role role) {
        if (Strings.isBlank(role.getId())) {
            roleService.save(role);
        } else {
            Role one = roleService.findById(role.getId());
            one.setDescription(role.getDescription());
            one.setStatus(role.getStatus());
            roleService.save(one);
        }

        return Message.success();
    }

    @DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Message delete(@PathVariable("id") String id) {
        roleService.delete(id);
        return Message.success();
    }
}
